package com.woniuxy.book.util;

import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.woniuxy.book.param.orderinfo.PagePayParam;
import com.woniuxy.book.service.dto.PayInfoDTO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class AlipayUtil {
    @Resource
    private AlipayClient alipayClient;

    /*
    * 网页支付方法
    * 参数：订单号，支付金额，支付主体、支付的文字内容、同步回调地址、异步回调地址
    * 返回值，一段包含表单的HTML信息
    * */
    public String pagePay(PagePayParam param) throws Exception {
        // 实例化网页支付请求对象
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //LocalDateTime now = LocalDateTime.now();
        //now.plusMinutes(2);
        //String expire = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //String s = DateUtil.DateTime2String(now);
        //String expire = now.toString().replaceAll("T", " ");
        // 设置参数
        String content = "{\"out_trade_no\":\"" + param.getOrderId() + "\"," + "\"total_amount\":\"" + param.getMoney()
                + "\"," + "\"subject\":\"" + param.getSubject() + "\"," + "\"body\":\"" + param.getBody() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\""+","+"\"timeout_express\":\"" + "2m" +"\""+"}";
        request.setBizContent(content);
        //设置同步回调和异步回调
        request.setReturnUrl(param.getReturnUrl());
        request.setNotifyUrl(param.getNotifyUrl());
        //执行网页支付请求
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        //判断支付宝响应结果
        if(response.isSuccess()) {
            //返回支付宝响应的支付表单html内容
            return response.getBody();
        }
        throw new Exception("发起支付失败");
    }

    /*
    * 查询订单支付状态
    * 参数：订单号
    * 返回值：boolean
    * */
    public PayInfoDTO selectPayState(String orderNum) throws AlipayApiException {
        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        //请二选一设置
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ orderNum+"\"}");
        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        //输出
        String orderInfo = JSONUtil.parseObj(result).get("alipay_trade_query_response").toString();
        String payCode = JSONUtil.parseObj(orderInfo).get("code").toString();
        if ("10000".equals(payCode)) {
            String payState = JSONUtil.parseObj(orderInfo).get("trade_status").toString();
            String payDate = null;
            if (!"WAIT_BUYER_PAY".equals(payState)) {
                payDate = JSONUtil.parseObj(orderInfo).get("send_pay_date").toString();
            }
            PayInfoDTO dto = new PayInfoDTO(payDate, payState);
            return dto;
        }else {
            PayInfoDTO dto = new PayInfoDTO(null, "TRADE_FAIL");
            return dto;
        }
    }
}
